package cn.edu.gzist.chapter10.controller;

import cn.edu.gzist.chapter10.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
public class TaskController {

    @Autowired
    private TaskService taskService;
    @RequestMapping("test01")
    public String sms(){
        taskService.sendSms();
        return "当前线程为: " + Thread.currentThread().getName();
    }

    @RequestMapping("test02")
    public String sms2() {
        long interval = 0;
        Future<Long>  interval1 = taskService.interval();
        Future<Long>  interval2 = taskService.interval();
        try {
            interval = interval2.get()+ interval1.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String times = "当前线程为: " + Thread.currentThread().getName()
                + "。任务全部完成，总耗时：" + interval + "毫秒";
        return times;
    }

    @RequestMapping("test03")
    public String doWorks() {
        long start = System.currentTimeMillis();
        Future<Boolean> a = taskService.doTask11();
        Future<Boolean> b = taskService.doTask22();
        Future<Boolean> c = taskService.doTask33();
        while (!a.isDone() || !b.isDone() || !c.isDone()) {
            if (a.isDone() && b.isDone() && c.isDone()) {
                break;
            }
        }
        long end = System.currentTimeMillis();
        String times = "当前线程为: " + Thread.currentThread().getName()
                + "。任务全部完成，总耗时：" + (end - start) + "毫秒";
        return times;

    }
}
